import { login, getInfo, logout, refreshToken } from '@/api/user'
import { getToken, setToken, removeToken, setExp, getExp, getTokenType, setTokenType, removeTokenType } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  exp: getExp(),
  getTokenType: getTokenType(),
  user_id: '',
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  user: {}
}

const mutations = {
  SET_TOKENTYPE:(state, type) => {
    state.type = type
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_USERID: (state, user_id) => {
    state.user_id = user_id
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_EXP: (state, exp) => {
    state.exp = exp
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_TokenType: (state, TokenType) => {
    state.TokenType = TokenType
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { token, overdue, tokentype } = response.headers
        commit('SET_TOKEN', token)
        commit('SET_EXP', overdue)
        commit('SET_TokenType', tokentype)
        setToken(token)
        setExp(overdue)
        setTokenType(tokentype)
        resolve()
        // window.location.href = '/dashboard'
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response.data

        if (!data) {
          reject('验证失败，请重新登录。')
        }

        const { role, name, id } = data.userInfo

        // roles must be a non-empty array
        if (!role || role.length <= 0) {
          reject('该账号没有角色，无法登录!')
        }
        commit('SET_USER', data.userInfo)
        commit('SET_ROLES', role)
        commit('SET_USERID', id)
        commit('SET_NAME', name)
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  refresh_token({ commit }) {
    return new Promise((resolve, reject) => {
      refreshToken().then(response => {
        commit('SET_TOKEN', '')
        removeToken()
        const token = response.token
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      })
    })
  },
  // user logout
  logout({ commit }) {
    return new Promise(resolve => {
      logout().then(res => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_TOKENTYPE', '')
        removeToken()
        removeTokenType()
        resetRouter()
        resolve()
      })
    })
  },

  // save avatar
  saveAvatar({ commit }, avatar) {
    return new Promise(resolve => {
      commit('SET_AVATAR', avatar)
      resolve()
    })
  },

  // save token
  saveToken({ commit }, token) {
    return new Promise(resolve => {
      commit('SET_TOKEN', token)
      setToken(token)
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
